import { BASE_URL } from './config'

// 创建请求实例
function request(options) {
  return new Promise((resolve, reject) => {
    // 构建完整URL
    let url = `${BASE_URL}${options.url}`
    
    // 直接从本地存储获取认证信息，避免访问store
    let userId = uni.getStorageSync('userId') || ''
    let token = uni.getStorageSync('token') || ''
    
    // 构建请求配置
    const requestOptions = {
      url: url,
      method: options.method || 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        'X-User-ID': userId || '',
        'X-Token': token || '',
        ...options.headers
      },
      success: (response) => {
        const { data, statusCode } = response
        
        // 处理成功响应
        if (statusCode >= 200 && statusCode < 300) {
          resolve(data)
        } else {
          // 处理401未授权错误
          if (statusCode === 401) {
            // 移除本地存储的用户信息
            uni.removeStorageSync('userState')
            uni.removeStorageSync('userId')
            uni.removeStorageSync('token')
            uni.showToast({
              title: '请重新登录',
              icon: 'none',
              duration: 1500
            })
            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/login/login'
              })
            }, 1500)
          }
          reject(new Error(data.error || `请求失败(${statusCode})`))
        }
      },
      fail: (error) => {
        console.error('请求错误:', error)
        reject(new Error('网络请求失败，请检查网络连接'))
      }
    }
    
    // 处理请求体
    if (options.data) {
      requestOptions.data = options.data
    }
    
    // 发送请求
    uni.request(requestOptions)
  })
}

export default request